/**
 * <p>Title: ServiceZMCMF3.java</p>
 * <p>Description: </p>
 * <p>Copyright: Baosight Software LTD.co Copyright (c) 2002</p>
 * <p>Company: Baosight Software</p>
 * @author 张小飞
 * @version 1.0
 * <pre>Histroy:
 *          2011-7-5 下午04:53:00  张小飞  Create
 *</pre>
 */
package com.baosight.sczx.zm.cm.service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.baosight.iplat4j.core.ei.EiBlock;
import com.baosight.iplat4j.core.ei.EiColumn;
import com.baosight.iplat4j.core.ei.EiConstant;
import com.baosight.iplat4j.core.ei.EiInfo;
import com.baosight.iplat4j.core.threadlocal.UserSession;
import com.baosight.iplat4j.ep.ServiceEPBase;
import com.baosight.sczx.common.zm.Utils;
import com.baosight.sczx.common.zm.basetools.StaticTools;
import com.baosight.sczx.common.zm.basetools.TablePk;
import com.baosight.sczx.common.zm.cInterface.cm.Depot;
import com.baosight.sczx.common.zm.cInterface.cm.MaterialBase;
import com.baosight.sczx.common.zm.cInterface.cs.SystemSettingCM;
import com.baosight.sczx.zm.cm.domain.ZMCMImportMaterial;
import com.baosight.sczx.zm.cm.domain.ZMCMMaterialBase;
import com.baosight.sczx.zm.cm.domain.ZMCMMaterialBasicInfo;
import com.baosight.sczx.zm.cm.domain.ZMCMMaterialType;
import com.baosight.sczx.zm.cm.domain.ZMCMReceiveGoodsInfo;
import com.baosight.sczx.zm.cm.domain.ZMCMStockPlanDetail;

/**
 * <p>Title: ServiceZMCMF3.java</p>
 * <p>Description: 到货登记管理-办理入库</p>
 * <p>Copyright: Baosight Software LTD.co Copyright (c) 2002</p>
 * <p>Company: Baosight Software</p>
 * @author 张小飞
 * @version 1.0
 * <pre>Histroy:
 *          2011-7-5 下午04:53:00  张小飞  Create
 *</pre>
 */
public class ServiceZMCMF3 extends ServiceEPBase {

	/**
	 * <p>Function: insert</p>
	 * <p>Description: 办理入库</p>
	 * <p>return value: ServiceZMCMF3</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2011-7-13下午08:04:46 张小飞
	 * </p>
	 *
	*/
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Override
	public EiInfo insert(EiInfo inInfo) {
		boolean isRepeat = validate(inInfo, "ZMCMImportMaterial.validate", new HashMap<String, String>());
		
		if(isRepeat) {
			inInfo.setStatus(-1);
			inInfo.setMsg("入库单号重复，请重新输入入库单号！");
			return inInfo;
		}
		else {
			//判断是否在结转日期之内
			String date1 = inInfo.getBlock("result").getCellStr(0, "fdNoteDate");
			if(date1 == null || "".equals(date1))//如果没有得到日期，默认为当前日期
			{
				date1 = StaticTools.getDate();
			}
			int result_int = MaterialBase.isInAccountDate(date1);
			if(result_int == -2)
			{
				inInfo.setStatus(-1);
				//StringBuffer msg = new StringBuffer("当前日期已经超出" + MaterialBase.getAccountDate(StaticTools.getDate())[2] + "月的记账范围，请在结转库存后，再办理入库！");
				StringBuffer msg = new StringBuffer("上个月没有做库存结转，请在结转库存后，再办理入库！");
				inInfo.setMsg(msg.toString());
				return inInfo;
			}
			if(result_int == 0)
			{
				inInfo.setStatus(-1);
				StringBuffer msg = new StringBuffer("该开单日期所在" + MaterialBase.getAccountDate(date1)[2] + "月的库存已经结转，无法办理入库！");
				inInfo.setMsg(msg.toString());
				return inInfo;
			}
			
			
			String fdKeyId = inInfo.getBlock("result").getCellStr(0, "fdKeyId");//到货登记明细主键
			String fdMaterialId = inInfo.getBlock("result").getCellStr(0, "fdMaterialId");
			//String fdMaterialInnerCode = inInfo.getBlock("result").getCellStr(0, "fdMaterialInnerCode");
			String fdImportType = inInfo.getBlock("result").getCellStr(0, "fdImportType");
			String fdNoteCode = inInfo.getBlock("result").getCellStr(0, "fdNoteCode");
			String invoiceSum = (inInfo.getBlock("result").getCellStr(0, "fdInvoiceSum")).equals("") ? "0.0" : inInfo.getBlock("result").getCellStr(0, "fdInvoiceSum");
			
			double fdInvoiceSum = Double.parseDouble(invoiceSum);
			double fdActualNumber = Double.parseDouble(inInfo.getBlock("result").getCellStr(0, "fdActualNumber"));
			double fdSum = Double.parseDouble(inInfo.getBlock("result").getCellStr(0, "fdSum"));
			
			Map map1 = new HashMap();
			map1.put("fdKeyId", fdMaterialId);
			List<ZMCMMaterialBasicInfo> result1 = dao.query("ZMCMMaterialBasicInfo.query", map1);
			double mbi = result1.get(0).getFdPrice();
			double fdPrice = mbi;
			
			//将物资基础信息中的单价，计入当前库存中物资的计划单价字段
			inInfo.getBlock("result").setCell(0, "fdPrice", mbi);
			
			Map map2 = new HashMap();
			map2.put("fdMaterialId", fdMaterialId);
			List<ZMCMMaterialBase> result2 = dao.query("ZMCMMaterialBase.query", map2);
			
			String fdYear = StaticTools.getYear();
			String fdMonth = StaticTools.getStringMonth();
			List month_list = dao.query("ZMCMMaterialBase.queryYearMonth", new HashMap());
			
			if(month_list.size() > 0)
			{
				fdYear = ((Map)month_list.get(0)).get("fdYear").toString();
				fdMonth = ((Map)month_list.get(0)).get("fdMonth").toString();
			}
			
			//如无该物资信息则进行新增操作
			if(result2.size() == 0){
				fdSum = fdPrice*fdActualNumber;
				inInfo.getBlock("result").setCell(0, "fdKeyId", TablePk.getInstance().getNextValue("T_CM_MATERIALBASE"));
				inInfo.getBlock("result").setCell(0, "fdDepotCode", Depot.getDepots().get(0).getFdDepotCode());
				inInfo.getBlock("result").setCell(0, "fdDepotName", Depot.getDepots().get(0).getFdDepotName());
				inInfo.getBlock("result").setCell(0, "fdYear", fdYear);
				inInfo.getBlock("result").setCell(0, "fdMonth", fdMonth.toString());
				inInfo.getBlock("result").setCell(0, "fdBusinessType", "正常入库");
				inInfo.getBlock("result").setCell(0, "fdNum", fdActualNumber);
				inInfo.getBlock("result").setCell(0, "fdSum", fdSum);
				
				if(fdInvoiceSum != Double.parseDouble("0.0"))
				{
					inInfo.getBlock("result").setCell(0, "fdActualPrice", BigDecimal.valueOf(fdInvoiceSum / fdActualNumber));
					inInfo.getBlock("result").setCell(0, "fdActualSum", fdInvoiceSum);
				}
				else
				{
					inInfo.getBlock("result").setCell(0, "fdActualPrice", fdPrice);
					inInfo.getBlock("result").setCell(0, "fdActualSum", BigDecimal.valueOf(fdSum));
				}
				
				if("一般入库".equals(fdImportType))
				{
					inInfo.getBlock("result").setCell(0, "fdHasinvoiceNum", fdActualNumber);
					inInfo.getBlock("result").setCell(0, "fdNoinvoiceNum", 0);
				}
				else if("估收入库".equals(fdImportType))
				{
					inInfo.getBlock("result").setCell(0, "fdHasinvoiceNum", 0);
					inInfo.getBlock("result").setCell(0, "fdNoinvoiceNum", fdActualNumber);
				}
				else
				{
					inInfo.getBlock("result").setCell(0, "fdHasinvoiceNum", 0);
					inInfo.getBlock("result").setCell(0, "fdNoinvoiceNum", 0);
				}
				inInfo.getBlock("result").setCell(0, "fdLastImportDate", StaticTools.getDate());
				
				super.insert(inInfo, "ZMCMMaterialBase.insertStorage");
			//更新库存中已存在物资信息	
			}else{
				double fdActualSum = result2.get(0).getFdActualSum();
				double fdNum = 	result2.get(0).getFdNum();
				fdSum = fdActualNumber*fdPrice;
				
				//计算实际单价，填入当前库存中物资的实际单价字段
				if(fdInvoiceSum != Double.parseDouble("0.0"))
				{
					inInfo.getBlock("result").setCell(0, "fdActualPrice", BigDecimal.valueOf((fdActualSum+fdInvoiceSum)/(fdNum + fdActualNumber)));
					inInfo.getBlock("result").setCell(0, "fdActualSum", BigDecimal.valueOf(fdActualSum+fdInvoiceSum));
				}
				else
				{
					inInfo.getBlock("result").setCell(0, "fdActualPrice", BigDecimal.valueOf((fdSum+fdActualSum)/(fdNum + fdActualNumber)));
					inInfo.getBlock("result").setCell(0, "fdActualSum", BigDecimal.valueOf(fdSum+fdActualSum));
				}
				
				if("一般入库".equals(fdImportType))
				{
					inInfo.getBlock("result").setCell(0, "fdHasinvoiceNum", 
							BigDecimal.valueOf(result2.get(0).getFdHasinvoiceNum()==null?0.0:result2.get(0).getFdHasinvoiceNum()+fdActualNumber));
					inInfo.getBlock("result").setCell(0, "fdNoinvoiceNum", result2.get(0).getFdNoinvoiceNum());					
				}
				else if("估收入库".equals(fdImportType))
				{
					inInfo.getBlock("result").setCell(0, "fdHasinvoiceNum", result2.get(0).getFdHasinvoiceNum());
					inInfo.getBlock("result").setCell(0, "fdNoinvoiceNum", BigDecimal.valueOf(result2.get(0).getFdNoinvoiceNum()+fdActualNumber));					
				}
				else
				{
					inInfo.getBlock("result").setCell(0, "fdHasinvoiceNum", result2.get(0).getFdHasinvoiceNum());
					inInfo.getBlock("result").setCell(0, "fdNoinvoiceNum", result2.get(0).getFdNoinvoiceNum());
				}
				
				//更新库存中已存在物资的数量、单价、计划单价等信息
				inInfo.getBlock("result").setCell(0, "fdMaterialId", fdMaterialId);
				inInfo.getBlock("result").setCell(0, "fdNum", BigDecimal.valueOf(fdNum + fdActualNumber));
				inInfo.getBlock("result").setCell(0, "fdSum", BigDecimal.valueOf((fdNum + fdActualNumber)*fdPrice));
				inInfo.getBlock("result").setCell(0, "fdLastImportDate", StaticTools.getDate());
				super.update(inInfo, "ZMCMMaterialBase.updateAfterStorage");
			}
			
			//办理入库
			String imKey = TablePk.getInstance().getNextValue("T_CM_IMPORTMATERIAL");
			inInfo.getBlock("result").setCell(0, "fdKeyId", imKey);//主键
			inInfo.getBlock("result").setCell(0, "fdDepotCode", Depot.getDepots().get(0).getFdDepotCode());
			inInfo.getBlock("result").setCell(0, "fdDepotName", Depot.getDepots().get(0).getFdDepotName());
			inInfo.getBlock("result").setCell(0, "fdEditor", UserSession.getUserId());
			inInfo.getBlock("result").setCell(0, "fdYear", MaterialBase.getAccountDate(date1)[0]);
			inInfo.getBlock("result").setCell(0, "fdMonth", MaterialBase.getAccountDate(date1)[1]);
			super.insert(inInfo, "ZMCMImportMaterial.insert");
			
			inInfo.getBlock("result").setCell(0, "fdKeyId", TablePk.getInstance().getNextValue("T_CM_IMPORTMATERIAL_DETAIL"));//主键
			inInfo.getBlock("result").setCell(0, "fdImportmaterialId", imKey);
			inInfo.getBlock("result").setCell(0, "fdSum", BigDecimal.valueOf(fdActualNumber*fdPrice));
			inInfo.getBlock("result").setCell(0, "fdPrice", fdPrice);
			EiInfo outInfo = super.insert(inInfo, "ZMCMImportmaterialDetail.insert");
			
			//将入库单据编号填入到货登记表中的入库单号字段
			inInfo.getBlock("result").setCell(0, "fdKeyId", fdKeyId);
			inInfo.getBlock("result").setCell(0, "fdImportnoteCode", fdNoteCode);
			super.update(inInfo, "ZMCMReceiveGoodsInfo.updateAfterStorage");
			
			return outInfo;
		}
	}
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public EiInfo insertMaterial(EiInfo inInfo)
	{
		String fdNewMaterial = inInfo.getBlock("material").getCellStr(0, "fdNewMaterial");
		String fdKeyId = "";
		String fdMaterialCode = inInfo.getBlock("material").getCellStr(0, "fdMaterialInnerCode");	
		if (fdMaterialCode.startsWith("root")){
			fdMaterialCode = fdMaterialCode.substring(4, fdMaterialCode.length());				
		}
		if("1".equals(fdNewMaterial))
		{
			String fdMaterialTypeInnerCode = inInfo.getBlock("material").getCellStr(0, "fdMaterialTypeInnerCode");	
			String fdMaterialLastCode = inInfo.getBlock("material").getCellStr(0, "fdMaterialLastCode");
			String fdMaterialInnerCode = fdMaterialTypeInnerCode + fdMaterialLastCode;
			//校验同一类别下没有重复的 ，且物资编码没有重复
			Map<String, String> params = new HashMap<String, String>();
			String fdMaterialTypeId = inInfo.getBlock("material").getCellStr(0, "fdMaterialTypeId");	
			params.put("fdMaterialTypeId", fdMaterialTypeId);
			params.put("fdMaterialLastCode", fdMaterialLastCode);
			params.put("fdMaterialInnerCode", fdMaterialTypeInnerCode+fdMaterialLastCode);//保证物资编号唯一
			boolean isRepeat = validate(inInfo, "ZMCMMaterialBasicInfo.validate", params);
			
			if(isRepeat) {
				return inInfo;
			}
			else {
				fdKeyId = TablePk.getInstance().getNextValue("T_CM_MATERIALBASICINFO");
				inInfo.getBlock("material").setCell(0, "fdKeyId", fdKeyId);//主键
				
				//为构造物资编码，去掉类别内码中root部分
				String noRootTypeInnerCode = fdMaterialTypeInnerCode;
				if (fdMaterialTypeInnerCode.startsWith("root")){
					noRootTypeInnerCode = fdMaterialTypeInnerCode.substring(4, fdMaterialTypeInnerCode.length());				
				}
				fdMaterialCode = noRootTypeInnerCode + fdMaterialLastCode;//物资编码=分类内码(去掉root)+物资尾码
				inInfo.getBlock("material").setCell(0, "fdMaterialCode", fdMaterialCode);
				inInfo.getBlock("material").setCell(0, "fdMaterialInnerCode", fdMaterialInnerCode);//物资内码=分类内码+物资尾码
				
				EiInfo outInfo = super.insert(inInfo, "ZMCMMaterialBasicInfo.insert", "material");
				if(outInfo.getStatus() == -1)
				{
					return outInfo;
				}
			}
		}
		else
		{
			fdKeyId = inInfo.getBlock("material").getCellStr(0, "fdMaterialId");
			inInfo.getBlock("material").setCell(0, "fdKeyId", fdKeyId);//主键
			EiInfo outInfo = super.update(inInfo, "ZMCMMaterialBasicInfo.update", "material");
			if(outInfo.getStatus() == -1)
			{
				return outInfo;
			}
		}
		
		inInfo.getBlock("result").setCell(0, "fdMaterialId", fdKeyId);
		inInfo.getBlock("result").setCell(0, "fdKeyId", inInfo.getBlock("material").getCell(0, "fdOldKeyId"));//主键
		inInfo.getBlock("result").setCell(0, "fdMaterialCode", fdMaterialCode);
		
		Map inMap = new HashMap();
		inMap.put("fdNewMaterialId", fdKeyId);
		inMap.put("fdKeyId", inInfo.getBlock("material").getCell(0, "fdOldKeyId"));
		//dao.update("ZMCMExportApplicationDetail.updateNoCodeMaterialId", inMap);
		dao.update("ZMCMReceiveGoodsInfo.updateNoCodeMaterialId", inMap);
		
		EiInfo outInfo = insert(inInfo);
		return outInfo;
	}
	
	/**
	 * 
	 * <p>Function: validate</p>
	 * <p>Description: 校验编号重复</p>
	 * <p>return value:boolean</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2011-7-18上午10:53:45 张小飞
	 * </p>
	 *
	 */
	@SuppressWarnings("rawtypes")
	private boolean validate(EiInfo inInfo, String sqlName, Map<String, String> params) {
		if(params == null) {
			params = new HashMap<String, String>();
		}
		
		String fdNoteCode = inInfo.getBlock("result").getCellStr(0, "fdNoteCode");
		
		params.put("fdNoteCode", fdNoteCode);
		
		List result = dao.query(sqlName, params);
		if(result != null && result.size() > 0) {
			inInfo.setStatus(-1);
			ZMCMImportMaterial im = (ZMCMImportMaterial)result.get(0);
			StringBuffer msg = new StringBuffer("提交失败，");
			if(im.getFdNoteCode() != null && im.getFdNoteCode().equals(fdNoteCode)) {
				msg.append(" 单据编号 ");
			}
			msg.append("重复！");
			inInfo.setMsg(msg.toString());
			return true;
		}
		return false;
	}
	
	/**
	 * 
	 * <p>Function: queryforCustomview</p>
	 * <p>Description: 物资信息的界面视图customview</p>
	 * <p>return value:EiInfo</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2011-7-18上午10:54:04 张小飞
	 * </p>
	 *
	 */
	public EiInfo queryforCustomview(EiInfo inInfo) {
		StaticTools.setQueryParameters(inInfo, "fdMaterialStatus", "在用", true);
		EiInfo outInfo = super.query(inInfo, "ZMCMMaterialBasicInfo.query",new ZMCMMaterialBasicInfo());
		return outInfo;
	}
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public EiInfo validateCode(EiInfo inInfo)
	{
		Map params = new HashMap();
		params.put("fdMaterialCode", inInfo.get("fdMaterialCode"));
		
		List result = dao.query("ZMCMMaterialBasicInfo.validate", params);
		if(result != null && result.size() > 0)
		{
			inInfo.setStatus(-1);
			StringBuffer msg = new StringBuffer("物资分类和物资尾码的组合重复！");
			inInfo.setMsg(msg.toString());
		}
		
		return inInfo;
	}

	/**物资分类查询
	 * <p>Function: type</p>
	 * <p>Description: </p>
	 * <p>return value: ServiceZMCMH0</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2011-6-7下午05:35:57 贾雪民
	 * </p>
	 *
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public EiInfo type(EiInfo info) 
	{
		String typeCode = "";
		Map inMap = new HashMap();
		String sqlmap = "ZMCMTypeManageMentSet.queryManageAllType";
		String isUseTypeManagement = SystemSettingCM.getInstance().getIsuseTypemanagement();
		if(isUseTypeManagement.equals("1"))
		{
			inMap.put("fdImportPeopleId", UserSession.getUserId());
			List _list = dao.query(sqlmap, inMap);
			List queryList = Utils.generateValidateData(_list);
			typeCode = "(FD_TYPE_ALL_CODE like ''";
			for(int j=0; j<queryList.size(); j++)
			{
				typeCode += " OR FD_TYPE_ALL_CODE like '" + queryList.get(j).toString() + "%'";
			}
			typeCode += ")";
		}
		else
		{
			sqlmap = "ZMCMMaterialType.type";
			List queryList = dao.query(sqlmap, inMap);
			
			typeCode = "(FD_TYPE_ALL_CODE like ''";
			for(int i=0; i<queryList.size(); i++)
			{
				Map _map = (Map)queryList.get(i);
				typeCode += " OR FD_TYPE_ALL_CODE like '" + _map.get("fdTypeCode").toString() + "%'";
			}
			typeCode += ")";
		}
		
		if(info.getBlock(EiConstant.queryBlock) == null)
		{
			info.addBlock(EiConstant.queryBlock);
		}
		info.getBlock(EiConstant.queryBlock).setCell(0, "fdTypeCodeStr", typeCode);
		
		info = super.query(info, "ZMCMMaterialType.queryallType", new ZMCMMaterialType());
		return info;
	}
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public EiInfo queryHasImportNoCodeMaterial(EiInfo inInfo)
	{
		EiInfo outInfo = new EiInfo();
		outInfo.set("fdNoteCode", queryNoteCode());
		String fdRequirePlan = "";
		if(inInfo.get("fdRequirePlan") != null)
		{
			fdRequirePlan = inInfo.get("fdRequirePlan").toString();
		}
		Map inMap = new HashMap();
		inMap.put("fdRequirePlan", fdRequirePlan);
		if("".equals(fdRequirePlan))
		{
			inMap.put("fdFromStock", "1");
		}
		List _list = dao.query("ZMCMReceiveGoodsInfo.queryHasImportNoCodeMaterial", inMap);
		if(_list.size() <= 0)
		{			
			return outInfo;
		}
		else
		{
			EiBlock block = outInfo.addBlock("queryResult");
			block.addBlockMeta((new ZMCMMaterialBasicInfo()).eiMetadata);
			block.addRow((ZMCMMaterialBasicInfo)_list.get(0));
			return outInfo;
		}
	}
	
	/**
	 * 
	 * <p>Function: queryNoteCode</p>
	 * <p>Description: </p>
	 * <p>return value:EiInfo</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2012-3-14上午10:48:09 wangkun
	 * </p>
	 *
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public String queryNoteCode()
	{
		List<Map> _list = new ArrayList<Map>();
		HashMap	params = new HashMap<String, String>();
		String startStr = "RK" + StaticTools.getDateDefault() + StaticTools.getTime().replaceAll(":", "");
		String defaultStr = startStr + "001";//定义格式
		_list = dao.query("ZMCMImportMaterial.querySerialNum", params);
		if(_list!=null && _list.size() > 0) {
			String str = _list.get(0).get("fdNoteCode").toString();
			defaultStr = convertStr(startStr, str);
		}
		
		return defaultStr;
	}
	
	public EiInfo batchInsertDetail(EiInfo inInfo)
	{
		String rgKey = inInfo.getString("fdReceiveId");

		if(inInfo.getBlocks().containsKey("subBlock"))
		{
			//插入到货明细表记录
			for(int i=0; i < inInfo.getBlock("subBlock").getRowCount(); i++)
			{
				if(hasRepeat(inInfo, rgKey))
				{
					inInfo.setStatus(-1);
					inInfo.setMsg("选择的记录中有已经在该到货记录中存在物资，不允许添加重复物资！");
					return inInfo;
				}
				String Sum = inInfo.getBlock("subBlock").getCellStr(i, "fdSum");
				String RecevieSum = inInfo.getBlock("subBlock").getCellStr(i, "fdRecevieSum");
				String ActualNum = inInfo.getBlock("subBlock").getCellStr(i, "fdActualNum");
				String Price = inInfo.getBlock("subBlock").getCellStr(i, "fdPrice");
				double fdSum = (Sum == null)? new Double(0):Double.valueOf(Sum.toString());
				double fdRecevieSum = (RecevieSum == null)? new Double(0):Double.valueOf(RecevieSum.toString());
				double fdActualNum = (ActualNum == null)? new Double(0):Double.valueOf(ActualNum.toString());
				double fdPrice = (Price == null)? new Double(0):Double.valueOf(Price.toString());
				
				if((fdActualNum-(fdSum-fdRecevieSum)) > 0)
				{
					inInfo.setStatus(-1);
					inInfo.setMsg("实收数量不能大于采购数量减已到货数量！");
					return inInfo;
				}
				
				String fdDetailId = inInfo.getBlock("subBlock").getCellStr(i, "fdKeyId");
				inInfo.getBlock("subBlock").setCell(i, "fdKeyId",  TablePk.getInstance().getNextValue("T_CM_RECEIVEGOODSINFO"));
				inInfo.getBlock("subBlock").setCell(i, "fdReceiveId", rgKey);
				inInfo.getBlock("subBlock").setCell(i, "fdDetailId", fdDetailId);
				inInfo.getBlock("subBlock").setCell(i, "fdValidateStatus", "到货");
				inInfo.getBlock("subBlock").setCell(i, "fdReceiveSum", BigDecimal.valueOf(fdActualNum*fdPrice));//此处必须这样赋值，不然会与采购计划表中字段“已到货数量（FD_RECEVIE_SUM）”发生冲突
			}
			
			super.insert(inInfo, "ZMCMReceiveGoodsInfo.insert", "subBlock");
		}
		
		//更新到货主表单据金额
		Map inMap = new HashMap();
		inMap.put("fdKeyId", rgKey);
		dao.update("ZMCMReceiveGoods.updateSumWithAllDetail", inMap);
		
		//更新采购计划中对应数据信息
		updateStockPlanInfo(inInfo, rgKey, false);
        return new EiInfo();	
	}
	
	private boolean hasRepeat(EiInfo eiInfo, String fdKeyId)
	{
		Map inMap = new HashMap();
		inMap.put("fdReceiveId", fdKeyId);
		List<ZMCMReceiveGoodsInfo> _list = dao.query("ZMCMReceiveGoodsInfo.query", inMap);
		
		for(int i=0; i<_list.size(); i++)
		{
			ZMCMReceiveGoodsInfo info = _list.get(i);
			String fdDetailId = info.getFdDetailId();
			
			for(int j=0; j<eiInfo.getBlock("subBlock").getRowCount(); j++)
			{
				if(eiInfo.getBlock("subBlock").getCellStr(j, "fdKeyId").equals(fdDetailId))
				{
					return true;
				}
				else
				{
					continue;
				}
			}
		}
		
		return false;
	}
	
	private void updateStockPlanInfo(EiInfo eiInfo, String fdKeyId, boolean deleteFlag)
	{
		Map inMap = new HashMap();
		inMap.put("fdReceiveId", fdKeyId);
		List<ZMCMReceiveGoodsInfo> _list = dao.query("ZMCMReceiveGoodsInfo.query", inMap);
		
		for(int i=0; i<_list.size(); i++)
		{
			ZMCMReceiveGoodsInfo info = _list.get(i);
			String fdDetailId = info.getFdDetailId();
			boolean flag = false;
			
			for(int j=0; j<eiInfo.getBlock("subBlock").getRowCount(); j++)
			{
				if(!eiInfo.getBlock("subBlock").getCellStr(j, "fdDetailId").equals(fdDetailId))
				{
					continue;
				}
				else
				{
					flag = true;
					break;
				}
			}
			
			if(!flag)
			{
				continue;
			}
			
			Map map = new HashMap();
			map.put("fdKeyId", fdDetailId);
			List<ZMCMStockPlanDetail> detail = dao.query("ZMCMStockPlanDetail.query", map);
			
			String fdStockPlanId = detail.get(0).getFdStockPlanId();
			//double fdSum = detail.get(0).getFdSum();
			double fdRecevieSum = detail.get(0).getFdRecevieSum();
			double fdActualNum = info.getFdActualNum();
			
			//更新采购计划明细信息
			map = new HashMap();
			if(deleteFlag)
			{
				map.put("fdRecevieSum", fdRecevieSum-fdActualNum);
			}
			else
			{
				map.put("fdRecevieSum", fdRecevieSum+fdActualNum);
			}
			
			map.put("fdKeyId", fdDetailId);
			dao.update("ZMCMStockPlanDetail.updateAfterAcceptance", map);
			
			map = new HashMap();
			map.put("fdStockPlanId", fdStockPlanId);
			List<ZMCMStockPlanDetail> detail1 = dao.query("ZMCMStockPlanDetail.query", map);
			
			map = new HashMap();
			map.put("fdPlanStatus", "全部到货");
			for(int j=0; j<detail1.size(); j++)
			{
				double sum = detail1.get(j).getFdSum();
				double recevieSum = detail1.get(j).getFdRecevieSum();
				
				//更新采购计划主表信息
				if(recevieSum != sum)
				{
					map.put("fdPlanStatus", "部分到货");
					break;	
				}
			}
			map.put("fdKeyId", fdStockPlanId);
			dao.update("ZMCMStockPlan.updateAfterAcceptance", map);
		}
	}
	
	/**
	 * 
	 * <p>Function: convertStr</p>
	 * <p>Description: </p>
	 * <p>return value:String</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2012-3-14上午10:48:03 wangkun
	 * </p>
	 *
	 */
	private String convertStr(String startStr, String str)
	{
		String str1 = str.substring(16,19);//第三部分的流水号
		int nub = Integer.parseInt(str1); 
		str1 = Integer.toString(nub+1);
		if(str1.length() == 1){
			return startStr+"00"+str1;
		}else if (str1.length() == 2)
		{
			return startStr+"0"+str1;
		}else
		{
			return startStr+str1;
		}
	}
}
